<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryForm.userName"
            placeholder="请输入用户名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryForm.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryForm.status"
            placeholder="用户状态"
            clearable
            style="width: 200px"
          >
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" style="width: 308px">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-bar">
        <div class="left-operations">
          <el-button
            v-permission="['system:user:add']"
            type="primary"
            icon="Plus"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            v-permission="['system:user:edit']"
            type="success"
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
          >
            修改
          </el-button>
          <el-button
            v-permission="['system:user:remove']"
            type="danger"
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
          >
            删除
          </el-button>
          <el-button
            v-permission="['system:user:import']"
            type="info"
            icon="Upload"
            @click="handleImport"
          >
            导入
          </el-button>
          <el-button
            v-permission="['system:user:export']"
            type="warning"
            icon="Download"
            @click="handleExport"
          >
            导出
          </el-button>
        </div>
        <div class="right-operations">
          <el-tooltip content="刷新" placement="top">
            <el-button icon="Refresh" circle @click="getList" />
          </el-tooltip>
        </div>
      </div>

      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="用户编号" prop="userId" width="80" />
        <el-table-column
          label="用户名称"
          prop="userName"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column label="用户昵称" prop="nickName" show-overflow-tooltip />
        <el-table-column label="部门" prop="dept.deptName" show-overflow-tooltip />
        <el-table-column label="手机号码" prop="phonenumber" width="120" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              v-permission="['system:user:edit']"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          width="160"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>{{ parseTime(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="160"
          class-name="small-padding fixed-width"
        >
          <template #default="{ row }">
            <el-tooltip content="修改" placement="top">
              <el-button
                v-permission="['system:user:edit']"
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(row)"
              />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-permission="['system:user:remove']"
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(row)"
              />
            </el-tooltip>
            <el-dropdown @command="(command) => handleCommand(command, row)">
              <el-button link type="primary" icon="DArrowRight" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-permission="['system:user:resetPwd']"
                    command="handleResetPwd"
                    icon="Key"
                  >
                    重置密码
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-permission="['system:user:edit']"
                    command="handleAuthRole"
                    icon="CircleCheck"
                  >
                    分配角色
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="cancel"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="userForm.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                v-model="userForm.deptId"
                :data="deptOptions"
                :props="{
                  value: 'id',
                  label: 'label',
                  children: 'children'
                }"
                value-key="id"
                placeholder="请选择归属部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="userForm.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="userForm.userId === undefined" label="用户名称" prop="userName">
              <el-input v-model="userForm.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="userForm.userId === undefined" label="用户密码" prop="password">
              <el-input
                v-model="userForm.password"
                placeholder="请输入用户密码"
                type="password"
                maxlength="20"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="userForm.sex" placeholder="请选择性别">
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
                <el-option label="未知" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="userForm.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="userForm.postIds" multiple placeholder="请选择岗位">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="userForm.roleIds" multiple placeholder="请选择角色">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status === '1'"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="userForm.remark"
                type="textarea"
                placeholder="请输入内容"
                maxlength="500"
                :rows="3"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" title="用户导入" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate"
            >
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import { 
  getUserList, 
  getUserInfo, 
  addUser, 
  updateUser, 
  deleteUser, 
  changeUserStatus,
  resetUserPwd,
  deptTreeSelect,
  exportUser,
  importTemplate as getImportTemplate,
  importData
} from '@/api/system/user'
import { getRoleList } from '@/api/system/role'
import { getPostList } from '@/api/system/post'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/global'
import Pagination from '@/components/Pagination/index.vue'

const userStore = useUserStore()

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref<number[]>([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 用户表格数据
const userList = ref<any[]>([])
// 弹出层标题
const dialogTitle = ref('')
// 是否显示弹出层
const dialogVisible = ref(false)
// 部门树选项
const deptOptions = ref<any[]>([])
// 岗位选项
const postOptions = ref<any[]>([])
// 角色选项
const roleOptions = ref<any[]>([])
// 日期范围
const dateRange = ref<string[]>([])

// 表单引用
const queryFormRef = ref<FormInstance>()
const userFormRef = ref<FormInstance>()
const uploadRef = ref()

// 查询参数
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phonenumber: '',
  status: '',
  deptId: undefined,
  beginTime: undefined,
  endTime: undefined,
})

// 用户表单数据
const userForm = reactive({
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: '',
  password: '',
  phonenumber: '',
  email: '',
  sex: '0',
  status: '0',
  remark: '',
  postIds: [],
  roleIds: [],
})

// 用户导入参数
const upload = reactive({
  open: false,
  title: '',
  isUploading: false,
  updateSupport: false,
  headers: { Authorization: 'Bearer ' + getToken() },
  url: '/api/system/user/importData',
})

// 表单校验
const userFormRules: FormRules = {
  userName: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' },
  ],
  nickName: [
    { required: true, message: '用户昵称不能为空', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '用户密码不能为空', trigger: 'blur' },
    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phonenumber: [
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
}

// 计算属性
const dialogFormTitle = computed(() => userForm.userId === undefined ? '添加用户' : '修改用户')

/** 查询用户列表 */
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryForm,
      beginTime: dateRange.value ? dateRange.value[0] : undefined,
      endTime: dateRange.value ? dateRange.value[1] : undefined,
    }
    const { data } = await getUserList(params)
    userList.value = data.rows
    total.value = data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 查询部门下拉树结构 */
const getDeptTree = async () => {
  try {
    const { data } = await deptTreeSelect()
    deptOptions.value = data
  } catch (error) {
    console.error('获取部门树失败:', error)
  }
}

/** 查询岗位列表 */
const getPostList = async () => {
  try {
    const { data } = await getPostList()
    postOptions.value = data
  } catch (error) {
    console.error('获取岗位列表失败:', error)
  }
}

/** 查询角色列表 */
const getRoleOptions = async () => {
  try {
    const { data } = await getRoleList()
    roleOptions.value = data
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryForm.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 排序触发事件 */
const handleSortChange = (column: any) => {
  queryForm.orderByColumn = column.prop
  queryForm.isAsc = column.order === 'ascending' ? 'asc' : 'desc'
  getList()
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  getDeptTree()
  getPostList()
  getRoleOptions()
  dialogVisible.value = true
  dialogTitle.value = '添加用户'
}

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset()
  getDeptTree()
  getPostList()  
  getRoleOptions()
  
  const userId = row?.userId || ids.value[0]
  try {
    const { data } = await getUserInfo(userId)
    Object.assign(userForm, data)
    userForm.postIds = data.postIds || []
    userForm.roleIds = data.roleIds || []
    dialogVisible.value = true
    dialogTitle.value = '修改用户'
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const userIds = row?.userId ? [row.userId] : ids.value
  
  try {
    await ElMessageBox.confirm(
      `是否确认删除用户编号为"${userIds}"的数据项？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await deleteUser(userIds)
    await getList()
  } catch (error) {
    console.log('取消删除')
  }
}

/** 用户状态修改 */
const handleStatusChange = async (row: any) => {
  const text = row.status === '0' ? '启用' : '停用'
  try {
    await ElMessageBox.confirm(`确认要"${text}""${row.userName}"用户吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    await changeUserStatus(row.userId, row.status)
    ElMessage.success(`${text}成功`)
  } catch (error) {
    row.status = row.status === '0' ? '1' : '0'
  }
}

/** 更多操作触发 */
const handleCommand = (command: string, row: any) => {
  switch (command) {
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleAuthRole':
      handleAuthRole(row)
      break
    default:
      break
  }
}

/** 重置密码按钮操作 */
const handleResetPwd = async (row: any) => {
  try {
    const { value: password } = await ElMessageBox.prompt(
      `请输入"${row.userName}"的新密码`,
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: '密码长度必须介于 5 和 20 之间',
      }
    )
    
    await resetUserPwd(row.userId, password)
  } catch (error) {
    console.log('取消重置密码')
  }
}

/** 分配角色操作 */
const handleAuthRole = (row: any) => {
  // TODO: 实现分配角色功能
  ElMessage.info('分配角色功能待实现')
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await ElMessageBox.confirm('是否确认导出所有用户数据项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    const params = {
      ...queryForm,
      beginTime: dateRange.value ? dateRange.value[0] : undefined,
      endTime: dateRange.value ? dateRange.value[1] : undefined,
    }
    
    await exportUser(params)
  } catch (error) {
    console.log('取消导出')
  }
}

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '用户导入'
  upload.open = true
}

/** 下载模板操作 */
const importTemplate = async () => {
  try {
    await getImportTemplate()
  } catch (error) {
    console.error('下载模板失败:', error)
  }
}

/** 文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response: any) => {
  upload.open = false
  upload.isUploading = false
  uploadRef.value?.clearFiles()
  
  if (response.code === 200) {
    ElMessage.success(response.msg)
    getList()
  } else {
    ElMessage.error(response.msg)
  }
}

/** 提交上传文件 */
const submitFileForm = () => {
  uploadRef.value?.submit()
}

/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (userForm.userId !== undefined) {
          await updateUser(userForm)
        } else {
          await addUser(userForm)
        }
        dialogVisible.value = false
        await getList()
      } catch (error) {
        console.error('提交用户信息失败:', error)
      }
    }
  })
}

/** 取消按钮 */
const cancel = () => {
  dialogVisible.value = false
  reset()
}

/** 表单重置 */
const reset = () => {
  Object.assign(userForm, {
    userId: undefined,
    deptId: undefined,
    userName: '',
    nickName: '',
    password: '',
    phonenumber: '',
    email: '',
    sex: '0',
    status: '0',
    remark: '',
    postIds: [],
    roleIds: [],
  })
  userFormRef.value?.resetFields()
}

// 初始化
onMounted(() => {
  getList()
  getDeptTree()
})
</script>

<style lang="scss" scoped>
.user-management {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left-operations {
  display: flex;
  gap: 8px;
}

.right-operations {
  display: flex;
  gap: 8px;
}

:deep(.el-table) {
  .el-table__cell {
    padding: 8px 0;
  }
}

.dialog-footer {
  text-align: center;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>
